package com.farm.tools.auth.cookie;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.farm.core.FarmService;
import com.farm.core.auth.domain.LoginUser;
import com.farm.tools.auth.cookie.util.CookieEncodeIMPL;
import com.farm.web.constant.FarmConstant;

/**
 * 通过cookie加载用户权限的过滤器（）
 * 
 * 还没有测试请测试
 * 
 * @author 王东
 * @version 20141109
 * 
 */
public class CookieCenterFilter implements Filter {
	/**
	 * cookie中存的userId的KEY
	 */
	public static final String COOKIE_USERID_KEY = "AUTHINDEX";

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpSession session = request.getSession();
		Cookie[] ck = request.getCookies();
		// 如果cookie中没有权限信息则清空当前权限信息
		if (ck != null) {
			String useridCode = getCookieValue(COOKIE_USERID_KEY, ck);
			if (useridCode == null || useridCode.trim().length() <= 0) {
				session.removeAttribute(FarmConstant.SESSION_USEROBJ);
			}
		}
		if (ck != null) {
			String useridCode = getCookieValue(COOKIE_USERID_KEY, ck);
			if (useridCode != null && useridCode.trim().length() > 0) {
				String userid = new CookieEncodeIMPL(request.getRemoteAddr())
						.deCode(useridCode);
				// 判断如果本session和用户session一致则不作处理
				if (userid != null) {
					// TODO 增加授权代码
					LoginUser user = FarmService.getInstance()
							.getAuthorityService().getUserById(userid);
					session.setAttribute(FarmConstant.SESSION_USEROBJ, user);
				}
			}
		}
		arg2.doFilter(arg0, arg1);
		return;
	}

	/**
	 * 从Cookies数组中获得某个匹配上KEY的Cookie值
	 * 
	 * @param key
	 * @param cookies
	 * @return
	 */
	private String getCookieValue(String key, Cookie[] cookies) {
		for (Cookie ck : cookies) {
			if (ck.getName().equals(key)) {
				return ck.getValue();
			}
		}
		return null;
	}

	// -----------------------------------------------------------
	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}

	@Override
	public void destroy() {
	}
}
